<?php
##############################################
#
#   首页
# @ Time : 2017-1-25 - 下午10:07:21
# @ Author : JiangYongWei <1085562810@qq.com>
# @ Encoding : UTF-8 language : PHP
#
##############################################
    
namespace Home\Controller;
use Home\Model\ActivityModel;
use Home\Model\ActivityCategoryModel;
use Admin\Model\AdminBaseModel;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;

class IndexController extends BaseController{
    
    public function _initialize(){
        parent::_initialize();
        //var_dump(cookie('mobileCode'));
        $this->assign('active', 'home');
    }
	
	/**
	 * 显示首页
	 */
    public function index(){
        $ip = getIP();
        $data = json_decode(httpUrl(C('map_city').'&ip='.$ip, $params, 1, $header = array(), $verify = false), true);
        if($data['status'] == 0){
            $city = $data['content']['address_detail']['city'];
        }else{
            $city = '广州市';
        }
        //$city = mb_substr($city,0,strlen($city)-3);//去掉最后一个汉字"市"
        $city = urldecode(str_replace('|','%',I('city'))) ? urldecode(str_replace('|','%',I('city'))) : $city;
        $this->assign('city', $city);
        $city_select = urlencode($city);
        $city_select = str_replace('%', '|', $city_select);
        $this->assign('city_select', $city_select);
        $city = mb_substr($city,0,strlen($city)-3);
        $activity_model = new ActivityModel();
        $activity_data = $activity_model->getActivity($city, I('activity_name'));
        $this->assign('activity', $activity_data[0]);
        //$this->assign('page', $data[1]);
        if ($_GET['is_ajax']) {
            $this->display('ajax_activity_index');
            exit;
        }
        //专家推荐
        $apply = M('apply')->field('id,user_name,type,headimgurl')->order('is_top desc,id asc')->limit(4)->select();
        $this->assign('apply',$apply);
        parent::benner();
        self::activityCategory();
        $this->display('activity_index');
    }
    
   
    
    /**
     * 活动分类
     */
    public function activityCategory(){
        $activity_category_model = new ActivityCategoryModel();
        $data = $activity_category_model->getCategory();
        $this->assign('category', $data);
    }
    
    /**
     */
    public function setEditor(){
        if(IS_GET){
            $this->display('textarea');
        }elseif(IS_POST){
            $data['text'] = $_POST['text'];
            $editor = M('editor');
            $row =  $editor->add($data);
            if($row !== false){
                $this->success('操作成功', U('setEditor'), 1);
            }else{
                $this->error('操作失败');
            }
            /* showData($_FILES);exit;
             var_dump($_POST);
             if($_FILES['files']['name']){
             $photo_img = AdminBaseModel::upload(200, 200, 'logo/');
             $param['store_logo'] = $photo_img['store_logo'];  //serialize($photo_img)
             if($param['store_logo']){
             @unlink($_SERVER['DOCUMENT_ROOT'].substr(__APP__, 1).$param['old_store_logo']);
             }
             } */
        }
         
    }
    
    /**
     * 发送短信验证
     * @param $mobile
     * @return mixed
     * @Date 201707
     * @Author Lin
     */
    public function send_sms()
    {

        require_once  './Api/dysms/vendor/autoload.php';    //此处为你放置API的路径
        Config::load();//加载区域结点配置
        
        $accessKeyId = 'LTAIKMwCxcxR4x4G';
        $accessKeySecret = 'w4qOX4d7qAnhuFVWdQQT5XQKMhQ3tR';
        $templateCode = 'SMS_85455041';   //短信模板ID

        //短信API产品名（短信产品名固定，无需修改）
        $product = "Dysmsapi";
        //短信API产品域名（接口地址固定，无需修改）
        $domain = "dysmsapi.aliyuncs.com";
        //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
        $region = "cn-hangzhou";
        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
        // 增加服务结点
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
        // 初始化AcsClient用于发起请求
        $acsClient = new DefaultAcsClient($profile);

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        // 必填，设置短信接收号码
        //$mobile = "13750006075";
        $mobile = I('phone_number');
        
        $request->setPhoneNumbers($mobile);    //$moblie是我前台传入的电话

        // 必填，设置签名名称
        $request->setSignName("江yongwei");      //此处需要填写你在阿里上创建的签名

        // 必填，设置模板CODE
        $request->setTemplateCode("SMS_85455041");    //短信模板编号

        $mobileCode = mt_rand(1000,9999);//验证码
        
        $smsData = Array(  // 短信模板中字段的值
            "code"=>"12345",
            "number"=>$mobileCode
        );

        //$smsData = array('username'=>$username);    //所使用的模板若有变量 在这里填入变量的值  我的变量名为username此处也为username

        $request->setTemplateParam(json_encode($smsData));

        //发起访问请求
        $acsResponse = $acsClient->getAcsResponse($request);

        //返回请求结果
        $result = json_decode(json_encode($acsResponse), true);
        //var_dump($result);
        //exit;
       //return $result;
        if($result['Code'] == 'OK')
        {
            //保存到cookie中
            cookie('mobileCode', $mobileCode, 120); // 验证码指定cookie保存时间3分钟
            $this->ajaxReturn(array('status'=>1,'message'=>'已发送！','mes'=>$result['Message']));
        }
        else
        {
            $this->ajaxReturn(array('status'=>2,'message'=>'发送失败！','mes'=>$result['Message']));
        }
    }
    
    /**
      * 检验验证码
     */
    public function check_code(){
        $code = I('code');
        if($code != cookie('mobileCode')){
            $this->ajaxReturn(array('status'=>2,'message'=>'验证码匹配不正确！'));
        }else{
            $this->ajaxReturn(array('status'=>1,'message'=>'验证码匹配正确！'));
        }
    }
    
    /**
     * 绑定手机成为正式会员
     * @date 2017年9月7日 - 上午11:15:53
     * @author JiangYongWei
     */
    public function applyUser(){
        if(IS_GET){
            $this->display('Users/apply_user');
        }else if(IS_POST){
            $phone_number = I('phone_number');
            $data = array('phone_number'=>$phone_number,'user_type'=>2);
            $result = M('users')->where("id = $this->user_id")->setField($data);
            $this->assign('title', '提示');
            $this->assign('message', '恭喜您，绑定手机成功，成为正式会员！快去参加活动吧。');
            $this->assign('jump_url', U("Users/index"));
            $this->assign('text', '用户中心');
            $this->display('Public/publish_tishi');
        }
    }
    
    /**
     * 申请会员类型才可发布活动
     */
    public function applyUserType() {
        if(IS_GET){
            $this->display('Users/apply_user_type');
        }else if(IS_POST){
            $data = I('post.');
            if($_FILES['prove_img']['name'] && $_FILES['card_img']['name']){
                $photo_img = AdminBaseModel::upload(900, 255, 'prove_img/');
                $data['prove_img'] = $photo_img['prove_img'];  //serialize($photo_img)
                $data['card_img'] = $photo_img['card_img'];
            }
            $data['user_id'] = $this->user_id;
            $data['autograph'] = htmlspecialchars($data['autograph']);
            $data['introduce'] = htmlspecialchars($data['introduce']);
            $data['note'] = htmlspecialchars($data['note']);
            $data['status'] = 1;
            $data['add_time'] = time();
            if($data['act'] == 'add'){
                $result = M('apply_user')->add($data);
                if($result){
                    $this->assign('title', '提示');
                    $this->assign('message', '资料已提交，等待审核。');
                    $this->assign('jump_url', U("Users/index"));
                    $this->assign('text', '用户中心');
                    $this->display('Public/publish_tishi');
                }else{
                    exit('操作失败');
                }
            }else if($data['act'] == 'edit'){
                $result = M('apply_user')->where("user_id = {$this->user_id}")->save($data);
                if($result){
                    $this->assign('title', '提示');
                    $this->assign('message', '资料已修改，等待审核。');
                    $this->assign('jump_url', U("Users/index"));
                    $this->assign('text', '用户中心');
                    $this->display('Public/publish_tishi');
                }else{
                    exit('操作失败');
                }
            }
        }
    }
    
    /**
     * 网站公告
     */
    public function notice(){
        $data['introduce'] = M('config')->where("name = 'introduce'")->getField('value');
        $data['store_name'] = M('config')->where("name = 'store_name'")->getField('value');
        $this->assign('data', $data);
        $this->display();
    }
    
}